﻿using IdentityModel.Client;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.Common
{
    public class TokenHandle
    {
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="identityUrl"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string GetToken(string identityUrl, string username, string password)
        {
            try
            {
                var client = new HttpClient();
                var config = new DiscoveryDocumentRequest() { Address = identityUrl, Policy = new DiscoveryPolicy() { RequireHttps = false } };
                var disco = client.GetDiscoveryDocumentAsync(config).Result; // 同步等待  

                if (disco.IsError)
                {
                    return disco.Error;
                }

                var tokenResponse = client.RequestPasswordTokenAsync(new PasswordTokenRequest
                {
                    Address = disco.TokenEndpoint,
                    ClientId = "SJ.Platform.Api",
                    ClientSecret = "secret",
                    UserName = username,
                    Password = password,
                    Scope = "SJ.Platform.Api SJ.Platform.LogApi"
                }).Result;

                if (tokenResponse.IsError)
                {
                    return tokenResponse.Error;
                }

                return tokenResponse.AccessToken;
            }
            catch (Exception ex)
            {
                // 处理异常  
                return ex.Message; // 或者其他错误处理逻辑  
            }
        }

        /// <summary>
        /// 解析token
        /// </summary>
        /// <param name="token"></param>
        public static IEnumerable<Claim> ParseToken(string token)
        {
            // 创建一个 JWT 解析器
            var handler = new JwtSecurityTokenHandler();

            // 解析 JWT，并验证签名（如果需要的话）
            var jwtToken = handler.ReadJwtToken(token);

            return jwtToken.Claims;
        }
    }
}
